<template>
	<view class="container">
		<view class="container-center">
			<view class="content">
				<view v-if="lockInfo" class="content-top" :style="{height: swiperHeight + 'px'}">
					<view class="lock-open">
						<view class="lock-info">
							<text class="info-top">{{ lockInfo.lockName }}</text>
						</view>
						<view class="open-lock">
							<view class="slide-unlock">
								<view class="slide-unlock_bgtop" :style="{opacity: opacityNum}"></view>
								<view class="slide-unlock_box">
									<movable-area style="width: 120rpx; height: 450rpx;" scale-area
										class="animation-box" :class="moveobj.disabled? 'active' : ''">
										<view class="top-box">
											<view class="image-box" :style="{opacity: 1 - opacityNum}">
												<image style="width: 60rpx; height: 60rpx;"
													src='../../../static/room/unlock.png' mode="aspectFill"></image>
											</view>
											<view class="point-box">
												<view class="image-box">
													<image style="width: 22rpx; height: 22rpx;"
														src="../../../static/room/arrows2.png" mode="aspectFill">
													</image>
												</view>
												<view class="image-box">
													<image style="width: 10rpx; height: 10rpx;"
														src="../../../static/room/point2.png" mode="aspectFill"></image>
												</view>
												<view class="image-box">
													<image style="width: 10rpx; height: 10rpx;"
														src="../../../static/room/point1.png" mode="aspectFill"></image>
												</view>
											</view>

											<movable-view class="image-box" style="width: 120rpx; height: 120rpx;"
												direction="all" :x="x" :y="y" :disabled="moveobj.disabled"
												@change="moveLock" @touchend="onTouchend()">
												<image style="width: 120rpx; height: 120rpx;"
													src="../../../static/room/lockslider.png" mode="aspectFill"></image>
											</movable-view>
										</view>
										<view style="height: 160rpx; width: 60rpx;">
										</view>
										<view style="flex: 1; display: flex; align-items: flex-start;">
											<text style="margin-top: 10px;">{{ moveobj.text }}</text>
										</view>
									</movable-area>
								</view>

							</view>
						</view>
						<view class="info-list">
							<uni-grid class="uni-grid-box" :column="4" :showBorder="false"
								@change="changePage($event, lockInfo)">
								<uni-grid-item class="uni-griditem-box"
									v-for="(item2, index1) in infolist.filter((item)=>item.isShow)" :index="index1"
									:key="index1">
									<view class="grid-item-box">
										<view class="image-box">
											<image style="width: 48rpx; height: 48rpx;" :src="item2.image"
												mode="aspectFit"></image>
										</view>
										<text class="text">{{ item2.text }}</text>
									</view>
								</uni-grid-item>
								<!-- 	<uni-grid-item class="uni-griditem-box" v-for="i in 2">
                                </uni-grid-item>
							</uni-grid>
						</view>
					</view>
				</view>
				<view v-else class="noInformation">
					<view class="no-content">
						<image style="width: 222rpx; height: 146rpx;" src="@/static/room/nocontent.png"
							mode="aspectFit"></image>
						<text class="no-num">暂无绑定门锁</text>
					</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	import Log from '@/utils/log.js';
	import bleUtils from '@/utils/BleUtils.js';
	import {
		cmd41,
		cmd21,
	} from '@/utils/cmd/index.js';
	import util from '@/utils/util.js';
	export default {
		data() {
			const curLock = this.$store.state.lockInfo;
			return {
				lockInfo: curLock,
				lockId: '',
				lockVersion: '',
				bleName: '', // 蓝牙名称
				lockMac: '',
				formatLockMac: '',
				deviceId: '',
				recordId: '', //门锁报文相关
				btnCanClick: true, // 登录按钮是否可以点击				
				timed: null,
				x: 0,
				y: 90,
				opacityNum: 0.1,
				swiperHeight: 130, //滑块的高度(单位px)				
				moveobj: {
					disabled: false,
					x: 0,
					y: 90,
					text: '上滑开锁'
				},
				userMobile: this.$userInfo.userMobile,
				userId: this.$userInfo.userId, //开锁接口用
				adminMob: '',
				adminPwd: '', // 用户密码 这个密码也应该从后台获取
				blePwd: '', // 蓝牙开锁密码 这个密码要从后台获取
				numPwd: '', // 数字开门密码
				infolist: [{
						image: '../../../static/index/numpassword.png',
						disimage: '../../../static/index/disnumpassword.png',
						text: '数字密码',
						path: '/pages/common/numPassword/showPassword',
						isShow: true
					},
					{
						image: '../../../static/index/face.png',
						disimage: '../../../static/index/face.png',
						text: '人脸开锁',
						path: '/pages/tenants/faceList/faceList',
						isShow: true
					},
					{
						image: '../../../static/index/usermag.png',
						disimage: '../../../static/index/guanli.png',
						text: '房客管理',
						path: '/pages/main/tenantManage?lockId=' + curLock.lockId,
						isShow: this.$userInfo.roleType == 1
					},
					{
						image: '../../../static/index/locksetting.png',
						disimage: '../../../static/index/dislocksetting.png',
						text: '门锁设置',
						path: '/pages/landlord/lockSetting/lockSetting',
						isShow: this.$userInfo.roleType == 1
					},
					{
						image: '../../../static/index/upgrade.png',
						disimage: '../../../static/index/upgrade.png',
						text: '门锁升级',
						path: '/pages/landlord/upgrade/upgrade',
						isShow: curLock.isUpgrade
					}
				],
				timer: null,
				timeOutSec: this.$sysInfo.timeOutSecs, // 超时秒数
			}
		},
		onLoad() {
			this.swiperHeight = this.$sysInfo.windowHeight - 120;
			console.log('====>', this.lockInfo)
			this.lockId = this.lockInfo.lockId || '';
			this.lockVersion = this.lockInfo.currentVersion || '';
			this.lockMac = (this.lockInfo.mac + '').toUpperCase() || '';
			this.bleName = this.lockInfo.bleName ? (this.lockInfo.bleName + '').toUpperCase() : '0905' + this.lockMac;
			this.adminMob = this.lockInfo.ownedInfo.managerMobile || '';
			this.adminPwd = this.lockInfo.ownedInfo.managerPassword || '';
			this.blePwd = this.lockInfo.bleOpenPassword || '';
			this.deviceId = this.lockInfo.deviceCode || '';
			if (this.lockMac) {
				this.formatLockMac = util.strInsert(this.lockMac, 2);
			}
			// console.log(this.bleName, this.adminMob, this.adminPwd, this.blePwd, this.deviceId, this.lockMac, this
			// 	.formatLockMac)
		},
		onShow() {

		},
		onUnload() {
			console.log('onUnload');
			if (this.timer) clearTimeout(this.timer);
			// 关闭蓝牙连接
			bleUtils.closeBLEConnection();
			// 关闭蓝牙适配器
			bleUtils.closeBluetoothAdapter();
		},
		methods: {
			// 跳转其他页面
			changePage(obj, item) {
				let itemObject = this.infolist[obj.detail.index];
				console.log(obj, '跳转其他页面====', item, itemObject);
				let owneInfo = item.ownedInfo;
				if (owneInfo == null || owneInfo == '') {
					util.toast('管理员信息缺失，请联系房东！');
					return false
				}
				uni.navigateTo({
					url: itemObject.path
				})
			},
			// 拖动开锁
			moveLock(e) {
				this.opacityNum = 1 - e.detail.y * 1 / this.y * 1
				// console.log(e, '拖动高度', e.detail.source, e.detail.y, '====', this.y, this.opacityNum)
				if (e.detail.source === "touch") {
					this.moveobj.x = e.detail.x;
					this.moveobj.y = e.detail.y;
				}
			},
			onTouchend() {
				this.x = this.moveobj.x;
				this.y = this.moveobj.y;
				this.timed = setTimeout(() => {
					// console.log('抬起', this.x, this.y);
					if (this.y === 0) {
						this.unlockFun()
					}
					this.y = 90;
				}, 30)
			},
			// 开锁
			unlockFun() {
				// util.loading('正在开锁');
				this.openLock();
			},
			async openLock() {
				try {
					if (!this.bleName) {
						util.alert('当前门锁缺少蓝牙名称');
						return;
					}
					if (!this.formatLockMac) {
						util.alert('当前门锁缺少mac');
						return;
					}
					if (!this.blePwd) {
						util.alert('当前门锁缺少蓝牙开锁密码');
						return;
					}
					if (!this.$sysInfo.locationEnabled) {
						util.alert('请先开启手机GPS定位服务!');
						util.hideLoading();
						return;
					}
					if (!this.$sysInfo.locationAuthorized) {
						// 让用户授权开启定位服务 为了让老版本的安卓手机能使用蓝牙
						await bleUtils.doAuthorize('scope.userLocation')
					}
					util.loading('开锁中...');
					// 打开蓝牙适配器
					await bleUtils.openBluetoothAdapter();
					await bleUtils.waitBleConnAndNotify(this.bleName, this.formatLockMac)
					// 监听当特征值发生变化的回调
					bleUtils.onBLECharacteristicValueChange((res) => {
						this.receiveBleData(res)
					});
					// 发送命令 先给锁校时 然后 再发开锁
					const cmdMsg = cmd21.generate();
					// const openMsg = cmd41.generate(this.adminMob, this.adminPwd, this.blePwd, '02');
					console.log('cmd21-->', cmdMsg);
					const cmd_buffer = bleUtils.myStringtoHex(cmdMsg);
					this.sendPacket(cmd_buffer);
				} catch (err) {
					console.log('bluetooth err--->', err)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			// 发送数据包给蓝牙设备
			async sendPacket(cmdData) {
				try {
					const unit8Array_data = new Uint8Array(cmdData);
					const data = unit8Array_data.buffer;
					await bleUtils.writeBLECharacteristicValue(data);
					this.timer = setTimeout(() => {
						clearTimeout(this.timer);
						util.hideLoading();
						bleUtils.closeBLEConnection();
					}, this.timeOutSec)
				} catch (err) {
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			async receiveBleData(res) {
				try {
					if (this.timer) clearTimeout(this.timer);
					console.log('receive bluetooth data--->', res);
					const data = res.substring(24, res.length - 2);
					const cmdWord = data.substr(0, 2);
					const resCode = data.substr(2, 2);
					if (cmdWord == '11') { //  校时的返回
						const cmdMsg = cmd41.generate(this.adminMob, this.adminPwd, this.blePwd, '02');
						console.log('cmd41--->', cmdMsg);
						const cmd_buffer = bleUtils.myStringtoHex(cmdMsg);
						this.sendPacket(cmd_buffer); // 发送开锁指令
					} else {
						// 关闭蓝牙连接
						bleUtils.closeBLEConnection();
						if (resCode != '01') {
							util.hideLoading();
							util.alert('开锁失败!');
							return;
						}
						const tempTimer = setTimeout(() => {
							clearTimeout(tempTimer);
							util.hideLoading();
							uni.showToast({
								title: '开锁成功',
								icon: 'success',
								duration: 2000
							});
						}, 1000);
					}
				} catch (err) {
					util.hideLoading();
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
		}
	}
</script>

<style>
	page {
		height: 100vh;
		background-color: #fff;
		/* 		background-image: url('https://mallfile.oss-cn-shanghai.aliyuncs.com/fault/kf/2021-04-09/top-mask.png') !important;
		background-size: contain !important; */
	}
</style>
<style lang="scss" scoped>
	.container {
		position: relative;
		background-color: #fff;
		height: 100vh;
		box-sizing: border-box;

		.container-center {
			height: 100vh;
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.content {
			background-color: #FFFFFF;
			padding: 40rpx 0rpx;
			border-radius: 20rpx;
			height: 100vh;

			.content-top {
				height: 100vh;

				.lock-open {
					height: 100%;
					display: flex;
					flex-direction: column;
				}

				.lock-info {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					margin-bottom: 20rpx;

					.info-top {
						font-size: 36rpx;
						font-weight: bold;
						color: #1F2642;
						display: inline-block;
						text-align: center;
						margin-bottom: 12rpx;
						width: 50%;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						-webkit-box-orient: vertical;
					}

					.enddate {
						display: -webkit-box;
						font-size: 24rpx;
						color: #8F92A0;
						margin: 12rpx 0;
					}
				}

				.open-lock {
					flex: 1;
					padding: 46rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.dis-slide-unlock {
						width: 450rpx;
						height: 450rpx;
						background: url('https://sharelife-prod.oss-cn-zhangjiakou.aliyuncs.com/sharelife/disopenlock.png');
						background-size: 100% 100%;
						z-index: 222;
					}

					.slide-unlock {
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: space-between;
						margin-bottom: 50rpx;
						width: 450rpx;
						height: 450rpx;
						background: url('https://sharelife-prod.oss-cn-zhangjiakou.aliyuncs.com/sharelife/d0fbfa0b65d742b1a9b8599e9bd98477-smartlock_ic_gallery_anim_bg.png');
						background-size: 100% 100%;
						position: relative;

						.slide-unlock_bgtop {
							position: absolute;
							width: 450rpx;
							height: 225rpx;
							background: url('https://sharelife-prod.oss-cn-zhangjiakou.aliyuncs.com/sharelife/08e5d4d2e45643e7ac5508e1a89860a8-smartlock_ic_anim_top.png');
							background-size: 100% 100%;
						}

						.slide-unlock_box {
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: space-between;
							font-size: 28rpx;
							color: #8F92A0;

							.animation-box {
								margin: 6rpx 0;
								display: flex;
								flex-direction: column;
								// justify-content: space-between;
								align-items: center;

								.top-box {
									height: 36%;
									display: flex;
									flex-direction: column;
									align-items: center;
									justify-content: space-between;

									.point-box {
										display: flex;
										flex-direction: column;
										align-items: center;
										justify-content: flex-start;

										.image-box {
											height: 30rpx;
										}
									}
								}

								.clickbth {
									transition: all 0.3s ease 0s;
								}

								.clickbth:hover {
									-webkit-transform: scale(1.2);
									-moz-transform: scale(1.2);
									-o-transform: scale(1.2);
									transform: scale(1.2);
								}
							}
						}

					}

					.switch-box /deep/ {
						display: flex;
						justify-content: space-between;
						align-items: center;
						font-size: 28rpx;
						color: #62677A;

						.uni-switch-wrapper {
							transform: scale(0.7);
						}
					}
				}

				.info-list /deep/ {
					margin-top: 10rpx;
					margin-bottom: 20rpx;
					padding: 18rpx 5px;
					background-color: #FBFBFC;
					border-radius: 20rpx;

					.uni-grid {
						justify-content: space-between;
					}

					.uni-grid-box {
						display: flex;
						flex-direction: row;
						flex-wrap: wrap;
						justify-content: space-around;
						align-items: center;

						// .uni-griditem-box:nth-last-child(2){
						// 	flex: 1;
						// }
						// .uni-griditem-box:last-child{
						// 	flex: 3;
						// }

						.uni-griditem-box {
							margin: 10rpx;
							position: relative;

							.grid-item-box {
								display: flex;
								flex-direction: column;
								justify-content: space-between;
								align-items: center;

								.text {
									font-size: 24rpx;
									color: #62677A;
								}

								.distext {
									color: #BBBDC6;
								}
							}

							.grid-tip {
								position: absolute;
								top: -30rpx;
								right: -50rpx;
								padding: 6rpx;
								border-top-left-radius: 8rpx;
								border-top-right-radius: 8rpx;
								border-bottom-right-radius: 8rpx;
								background: #FF521C;
								color: #fff;
								font-size: 18rpx;
							}
						}

					}

					// .uni-grid-box::after{
					// 		content: "";
					// 		width: 240rpx;
					// 		height: 240rpx;
					// 		margin: 10rpx;
					// 	}

				}
			}



			.noInformation {
				height: calc(100vh - 350rpx);

				.no-content {
					display: flex;
					flex-direction: column;
					align-items: center;
					padding: 240rpx 0;

					.no-num {
						font-size: 28rpx;
						color: #8F92A0;
					}
				}
			}
		}
	}

	.testBtn {
		position: absolute;
		top: 400rpx;
		width: 220rpx;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #FFFFFF;
		text-align: center;
		border-radius: 10rpx;
	}
</style>